<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/15 0015
 * Time: 10:41
 */

namespace app\api\controller;
use app\api\model\Forwarding;
use app\api\model\ImageInfos;
use app\api\model\Likes;
use lib\ImgCompare;
use lib\JSSDK;
use think\Controller;
use think\Request;
use think\Db;

class DetailsController extends Controller
{
    private $user_info;
    private $openid;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->openid = $this->request->param('openid');
        if(!$this->openid){
            respon(210,'参数错误');
        }
        $this->user_info = json_decode($this->redis->get($this->openid));
        if(!$this->user_info){
            respon(210,'用户信息错误！');
        }
    }

    public function test(){
        $wechat = new JSSDK();
        $touser = 'od84A5TZF9JvEruwY2x4tKlwjgyw';
        $template_id = 'iVsH1yVfNvjAuWEj4IpRDzTXFGOaA01L705rUXoGG_s';
        $page = 'pages/index/index';
        $formId = '1526972894894';
        //示例数据根据消息模板填充
        $data = array(
            'keyword1'=>array('value'=>'测试','color'=>'#7167ce'),
            'keyword2'=>array('value'=>'测试','color'=>'#7167ce'),
            'keyword3'=>array('value'=>'测试','color'=>'#7167ce'),
            'keyword4'=>array('value'=>'测试','color'=>'#7167ce'),
            'keyword5'=>array('value'=>'测试','color'=>'#7167ce')
        );
        $res = $wechat->sendTemplate($touser,$template_id,$page,$data,$formId);
        if($res){
            if(!$res['errcode']!=0){
                return respon(200,'失败！');
            }
            return respon(200,'成功！');
        }
    }


    public function getReviews(){
        $movie_id=input('post.movie_id');
        if(!$movie_id){
            respon(210,'缺少电影id');
        }
        //查询自己关于这个电影是否有评论
        $user_id = $this->user_info->id;
        $s_review = db('film_review')->where(['movie_id' =>$movie_id,'user_id'=>$user_id,'type'=>1])->find();
        $l_review = db('film_review')->where(['movie_id' =>$movie_id,'user_id'=>$user_id,'type'=>2])->find();
        $datas['self_s_review'] = $s_review?$s_review:null;
        $datas['self_l_review'] = $l_review?$l_review:null;
        $datas['movie_id'] = $movie_id;
        //查询影评
        $s_reviews =  movies_review('',$movie_id,1);
        $datas['s_reviews'] = $s_reviews?$this->getLikes($s_reviews):null;
        $l_reviews =  movies_review('',$movie_id,2);
        $datas['l_reviews'] = $l_reviews?$l_reviews:null;
        //查询是否收藏
        $res = db('collections')->where(['movie_id' =>$movie_id,'user_id'=>$user_id])->find();
        if(!$res){
            $datas['is_collection'] = 0;
        }else{
            $datas['is_collection'] = $res['is_valid']==1?1:0;
        }
        respon(200,$datas);
    }


    private function getLikes($reviews){
        foreach ($reviews as &$v){
            $likes_res = Likes::getOne('id',['review_id'=>$v['id'],'user_id'=>$this->user_info->id,'is_valid'=>1]);
            $v['is_likes'] = $likes_res?1:0;
        }
        return $reviews;
    }

    /**
     * @throws \think\exception\DbException
     * 添加转发记录
     */
    public function addForward(){
        $user_id = $this->user_info->id;
        $content_id=input('post.content_id');
        $type=input('post.type',1);
        $forward_target=input('post.forward_target',1);
        $content_title=input('post.content_title');
        if(!$content_id || !$content_title){
            respon(200,'分享错误！');
        }
        $add_data = [
            'user_id'=>$user_id,
            'type'=>$type,
            'forward_target'=>$forward_target,
            'content_id'=>$content_id,
            'title'=>$content_title
        ];
        $res = Forwarding::create($add_data);
        if(!$res){
            respon(200,'分享失败！');
        }

        respon(200,'分享成功！');
    }

    /*
     * 影人互评论,先查询是否评论过，是的话则返回评论内容
     * $user_id 评论人id
     * $other_id 被评人id
     * */

    public function select_figure_review(){
        $openid=input('post.openid');
        $other_id=input('post.user_id');
        if(!input('post.openid')||!input('post.user_id')){
            return respon(230,"openid未获取到");
        }
        $user_id=$this->user_info->id;
        $where='user_id = '.$user_id.' and other_id = '.$other_id;
        $result=Db::name('figure_review')->where($where)->field('content,pag')->find();
        if($result){
            return respon(200,$result);
        }else{
            return respon(270,'未查询到数据');
        }
    }


    /*
     * 影人互评论,更新评论的内容
     * $user_id 评论人id
     * $other_id 被评人id
     * */

    public function update_figure_review(){
        $data=array();
        $openid=input('post.ope nid');
        $other_id=input('post.user_id');
        $content=input('post.content');
        $t_pag=input('post.pag');
        $pag=str_replace(array('&quot;','[',']',"'"), '', $t_pag);
        if($content==''){
            return respon(210,'参数错误');
        }
        if(!input('post.openid')||!input('post.user_id')){
            return respon(230,"openid未获取到");
        }
        $user_id=$this->user_info->id;
        $data['user_id']=$user_id;
        $data['other_id']=$other_id;
        $data['content']=$content;
        $data['pag']=$pag;
        $where='user_id = '.$user_id.' and other_id = '.$other_id;
        $result=Db::name('figure_review')->where($where)->field('content,pag')->find();
        if($result){
            $re=Db::name('figure_review')->where($where)->update(['content'=>$content,'pag'=>$pag]);
            if($re){
                return respon(200,'评论成功！');
            }else{
                return respon(250,'写入失败');
            }

        }else{
            $re=Db::name('figure_review')->insert($data);
            if($re){
                return respon(200,'评论成功！');
            }else{
                return respon(250,'写入失败');
            }
        }
    }

    /*
     * 写入电影评论
     * $user_id 评论人id
     * $movie_id 评论电影id
     * $movie_name 电影，名字
     * $content 评论内容
     * $type 评论类型 1短评，2长评
     * $title 电影长评标题
     * $rate 电影评分
     * */

    public function writeMovieReview(){
        $data=array();
        $content=input('post.content');
        $data['movie_id']=input('post.movie_id');
        $data['movie_name']=input('post.movie_name');
        $data['rate']=input('post.rate');
        $data['type']=input('post.type');
        if($data['type'] == 2){
            $data['title']=input('post.title');
            $data['status']=2;
            $data['l_review']=$content;
        }else{
            $data['status']=1;
            $data['s_review']=$content;
        }
        if(!$content || !$data['rate']){
            respon(210,'参数错误！');
        }
        $data['user_id']=$this->user_info->id;
        $result=Db::name('film_review')->where(['movie_id'=>$data['movie_id'],'user_id'=>$data['user_id'],'type'=>$data['type']])->find();
        if($result){
            respon(210,'不能重复发布！');
        }
        $data['created_at'] = date('Y-m-d H:i:s',time());
        $result=Db::name('film_review')->insert($data);

        if($result==1){
            return respon(200,'评论成功!');
        }else{
            return respon(250,'写入失败');
        }
    }

    /**
     * 修改评论
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function editMovieReview(){
        $content=input('post.content');
        $review_id=input('post.review_id');
        $rate=input('post.rate');
        $title=input('post.title');
        $type=input('post.type');
        if(!in_array($type,[1,2])){
            respon(210,'参数错误！');
        }
        if($type==1){
            $date['s_review'] = $content;
        }else{
            $date['l_review'] = $content;
            $date['title'] = $title;
        }
        $date['rate']=$rate;
        if(!$content || !$review_id || !is_numeric($rate)){
            respon(210,'参数错误！');
        }
        $user_id = $this->user_info->id;
        $res = db('film_review')->where(['user_id' =>$user_id,'id'=>$review_id])->update($date);
        if($res){
            respon(200,'修改成功!');
        }else{
            respon(250,'修改失败!');
        }
    }


    /*
     * 电影评论追评
     * $user_id 评论人id
     * $content 评论内容
     * $to_fe_id 评论的帖子id
     * */

    public function Follow_up(){
        $content=input('post.content');
        $review_id=input('post.review_id');
        $to_com_id=input('post.to_com_id');
        if( !$content  || !$review_id){
            return respon(210,'参数错误');
        }
        $data=array();
        $data['user_id']=$this->user_info->id;
        $data['content']=$content;
        $data['to_com_id']=$to_com_id;
        $data['review_id']=$review_id;
        $data['created_at']=date('Y-m-d H:i:s', time());
        $result=Db::name('comments')->insert($data);
        if($result){
            Db::name('film_review')->where('id = '.$to_com_id)->setInc('comment_count');
            return respon(200,'评论成功!');
        }else{
            return respon(250,'写入失败');
        }

    }


    /**
     * 影评页面
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getReviewList(){
        $page=input('post.page')?input('post.page'):0;
        $arr=wechat_page($page,'5');
        $offset=$arr['offset'];
        $length=$arr['length'];
        $where['fr.status'] = 1;
        $where['fr.type'] = 2;
        $re=Db::name('film_review')->alias('fr')->join('movies m','m.id = fr.movie_id','left')->where($where)->field('fr.id,fr.user_id,fr.rate,fr.s_review,fr.title,fr.l_review,fr.like_count,fr.comment_count,fr.created_at,m.name,m.movie_image')->limit($offset,$length)->select();
        if(!$re){
            respon(210,'暂无数据');
        }
        foreach ($re as &$v){
            $where='u.id = '.$v['user_id'];
            $user_info=Db::name('user')->alias('u')->join('user_extend ue','u.phone = ue.phone','left')->where($where)->field('u.id,ue.nickname,ue.gender,ue.province,ue.work,ue.avatar_url')->find();
            $v['user_info'] = $user_info?$user_info:null;
            $v['created_at'] = substr($v['created_at'],0,10);
        }
        $this->getLikes($re);
        $data['reviews'] = $re;
        if($data){
            return respon(200,$data);
        }else{
            return respon(250,'写入失败');
        }
    }


    /*
     * 获得电影评论
     * $movie_id 电影id
     * */

    public function getMovieReview(){
        $movie_id=input('post.movie_id');
        $type=input('post.type');
        $page=input('post.page')?input('post.page'):0;
        if(!$movie_id){
            respon(210,'参数错误');
        }
        if(!in_array($type,[1,2])){
            respon(210,'参数错误');
        }
        $arr=wechat_page($page,'5');
        $offset=$arr['offset'];
        $length=$arr['length'];
        $where['movie_id'] = $movie_id;
        $where['status'] = 1;
        $where['type'] = $type;
        //计算数量
        $count = Db::name('film_review')->where($where)->count('*');
        $data['count']=$count;
        $re=Db::name('film_review')->where($where)->field('id,user_id,rate,s_review,title,l_review,like_count,comment_count,created_at')->limit($offset,$length)->select();
        foreach ($re as &$v){
            $where='u.id = '.$v['user_id'];
            $user_info=Db::name('user')->alias('u')->join('user_extend ue','u.phone = ue.phone','left')->where($where)->field('u.id,ue.nickname,ue.gender,ue.province,ue.work,ue.avatar_url')->find();
            $v['user_info'] = $user_info?$user_info:null;
        }
        //判断是否是点赞
        $this->getLikes($re);
        $data['reviews'] = $re;
        if($data){
            return respon(200,$data);
        }else{
            return respon(250,'写入失败');
        }

    }


    /*
     * 获得电影评论追评
     * $review_id 长评id
     * */

    public function get_Follow_up(){
        $review_id=input('post.review_id');
        $page=input('post.page')?input('post.page'):0;
        if(!$review_id){
            respon(210,'参数错误');
        }
        $arr=wechat_page($page,'5');
        $offset=$arr['offset'];
        $length=$arr['length'];
        $where='to_fe_id = '.$review_id;
        $re=Db::name('comments')->where($where)->field('id,user_id,content,created_at')->limit($offset,$length)->select();
        foreach ($re as $k=>$v){
            $where='u.id = '.$v['user_id'];
            $op=Db::name('user')->alias('u')->join('user_extend ue','u.phone = ue.phone','left')->where($where)->field('u.id,ue.nickname,ue.gender,ue.province,ue.work,ue.avatar_url')->select();
            if($op[0]){
                $re=array_merge($op[0],$v);
            }
        }
        if($re){
            return respon(200,$re);
        }else{
            return respon(250,'写入失败');
        }

    }

    /**
     * 长评的详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getReviewInfo(){
        $review_id=input('post.review_id');
        $page=input('post.page')?input('post.page'):0;
        if(!$review_id){
            respon(210,'参数错误');
        }
        $result = Db::name('film_review')->where(['id'=>$review_id])->find();
        if(!$result){
            respon(210,'暂无数据');
        }
        $user_info=Db::name('user')->alias('u')->join('user_extend ue','u.phone = ue.phone','left')->where(['u.id'=>$result['user_id']])->field('u.id,ue.nickname,ue.gender,ue.province,ue.work,ue.avatar_url')->find();
        $result['user_info'] = $user_info?$user_info:null;
        $arr=wechat_page($page,'10');
        $offset=$arr['offset'];
        $length=$arr['length'];
        $res=Db::name('comments')->where(['review_id'=>$review_id])->limit($offset,$length)->select();
        if($res){
            foreach ($res as &$v){
                $v['father_review'] = Db::name('comments')->where(['id'=>$v['to_com_id']])->find();
                $user_info=Db::name('user')->alias('u')->join('user_extend ue','u.phone = ue.phone','left')->where(['u.id'=>$v['user_id']])->field('u.id,ue.nickname,ue.gender,ue.province,ue.work,ue.avatar_url')->find();
                $v['user_info'] = $user_info?$user_info:null;
            }
        }
        $datas['review'] = $result;
        $datas['comments'] = $res?$res:null;
        respon(200,$datas);
    }

    /*
     * 评论点赞统计
     * $review_id 评论id
     * $type 点赞类型，1影评 2.追评
     * $user_id 用户id
     * */
    public function setLike(){
        $review_id=input('post.review_id');
        $type=input('post.type');
        if(!$review_id || !$type){
            return respon(210,'参数错误');
        }
        $user_id=$this->user_info->id;
        $where='user_id = '.$user_id.' and review_id = '.$review_id.' and type = '.$type;
        $re=Db::name('likes')->where($where)->field('id,is_valid')->find();
        //如果没有点赞 则添加点赞数据
        if($re){
            $status = $re['is_valid']==1?0:1;
            $result=Db::name('likes')->where($where)->update(['is_valid'=>$status]);
        }else{
            $data['user_id']=$user_id;
            $data['type']=$type;
            $data['review_id']=$review_id;
            $data['created_at']=date('Y-m-d H:i:s', time());
            $result=Db::name('likes')->insert($data);
            $status = 1;
        }
        if($type==1){
            if($status==1){
                $like=Db::name('film_review')->where('id = '.$review_id)->setInc('like_count');
            }else{
                $like=Db::name('film_review')->where('id = '.$review_id)->setDec('like_count');
            }
        }
        if($type==2){
            $like=Db::name('comments')->where('id = '.$review_id.' and user_id = '.$user_id)->setInc('like_count');
        }
        //$token = reward_token($user_id, 4);
        if($result){
            return respon(200,'点赞成功!');
        }else{
            return respon(250,'写入失败');
        }
    }

    /*
     *
     * 电影票根识别
     * */
    public function Compared_img(){
        $openid=input('post.openid');
        $url=input('post.url');
        if(!$openid || !$url){
            respon(210,'参数错误');
        }
        $user_id = $this->user_info->id;
        $img = new ImgCompare();
        $imagg = imagecreatefromjpeg($url);
        $value = $img->getHashValue($imagg);
        $hash = hash('MD5',$value);
        $ress = ImageInfos::get(['image_hash'=>$hash]);
        if($ress){
            respon(250,'该图片已经上传过');
        }
        //获取图片
        $image = file_get_contents($url);
        $res = $this->baidu($image);
        if(!isset($res['error_code']) ){
            $str = implode('',array_column($res['words_result'],'words'));
            if((strpos($str,'电影') !==false) || (strpos($str,'影院') !==false) || (strpos($str,'影片') !==false) || (strpos($str,'片名') !==false ) || (strpos($str,'影厅') !==false)){
                if($res){
                    $result = ImageInfos::get(['user_id'=>$user_id,'image_info'=>md5($str)]);
                    if($result){
                        respon(270,'对不起,您的票根已经使用过了');
                    }else{
                        $res = ImageInfos::create(['user_id'=>$user_id,'image_url'=>$url,'image_info'=>md5($str),'created_at'=>date('Y-m-d H:i:s'),'image_hash'=>$hash]);
                        $token = reward_token($user_id, 7);
                        if($res && $token){
                            respon(200,'上传成功,获得666Token!');
                        }else{
                            respon(250,'写入失败');
                        }
                    }
                }
                respon(250,'写入失败');
            }
        }
        respon(210,'上传的图片可能不是电影票,请重新上传再试！');
    }
}